package com.aiju.cash.ui.main;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.base.window.CustomPopWindow;
import com.aiju.bean.BlotterInfo;
import com.aiju.cash.R;
import com.aiju.cash.core.api.BlotterApi;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.MessageApi;
import com.aiju.cash.ui.pay.manager.PrintManager;
import com.aiju.utils.L;
import com.aiju.utils.PriceUtil;
import com.aiju.utils.T;
import com.aiju.widgit.layout.LeftRightTextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import okhttp3.Call;

/**
 * @author: 佐为
 * @date: 2017-01-04 10:09
 * @version: V1.0
 * @Description: 流水详情
 */
public class BlotterInfoActvity extends BaseTitleActivity {

    private String id;

    private TextView price, goodNum;

    private TextView textView0;
    private TextView textView1, textView2, textView3;
    private TextView textView31, textView32;
    private TextView textView4, textView5, textView6;
    private TextView textView7, textView8, textView9;
    private TextView textView10, textView11, textView12;
    private ListView mOrderListView;

    private int type;
    private String title = "流水明细";

    private View imageView;

    private BlotterInfo info;

    private LeftRightTextView t1, t2, t3, t4, t5, t6, t7, t8;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blotter_info);
        id = getIntent().getStringExtra("id");
        type = getIntent().getIntExtra("type", 0);
        title = getIntent().getStringExtra("title");

        setCenterTitle(title);

        t1 = (LeftRightTextView) findViewById(R.id.ly_refund_1);
        t2 = (LeftRightTextView) findViewById(R.id.ly_refund_2);
        t3 = (LeftRightTextView) findViewById(R.id.ly_refund_3);
        t4 = (LeftRightTextView) findViewById(R.id.ly_refund_4);
        t5 = (LeftRightTextView) findViewById(R.id.ly_refund_5);
        t6 = (LeftRightTextView) findViewById(R.id.ly_refund_6);
        t7 = (LeftRightTextView) findViewById(R.id.ly_refund_7);
        t8 = (LeftRightTextView) findViewById(R.id.ly_refund_8);
        t1.getContentTextView().setTextColor(Color.parseColor("#1eab75"));


        imageView = mAiJuTitleBarView.getRightTextView();
/*        imageView = new ImageView(this);
        imageView.setImageResource(R.mipmap.icon_more);
        mAiJuTitleBarView.setCustomizedRightView(imageView);
        */
        setRightTitle("退款");
        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //pop(v);
                if (info != null) {
                    Intent intent = new Intent(BlotterInfoActvity.this, RefundActivity.class);
                    intent.putExtra("info", info);
                    startActivity(intent);
                }
            }
        });
        if (title.contains("退款")) {
            findViewById(R.id.ly_blotter_refund).setVisibility(View.VISIBLE);
            findViewById(R.id.btn_refund).setVisibility(View.VISIBLE);
            findViewById(R.id.ly_blotter_blotter).setVisibility(View.GONE);

            //退款 商品详情隐藏
            findViewById(R.id.ly_good_info).setVisibility(View.GONE);
            imageView.setVisibility(View.GONE);
            mAiJuTitleBarView.setRightOnClickListener(null);
        }

        price = (TextView) findViewById(R.id.tv_bloter_info_price);
        goodNum = (TextView) findViewById(R.id.tv_good_num);

        textView0 = (TextView) findViewById(R.id.tv_bloter_info_0);
        textView1 = (TextView) findViewById(R.id.tv_bloter_info_1);
        textView2 = (TextView) findViewById(R.id.tv_bloter_info_2);
        textView3 = (TextView) findViewById(R.id.tv_bloter_info_3);
        textView31 = (TextView) findViewById(R.id.tv_bloter_info_31);
        textView32 = (TextView) findViewById(R.id.tv_bloter_info_32);
        textView4 = (TextView) findViewById(R.id.tv_bloter_info_4);
        textView5 = (TextView) findViewById(R.id.tv_bloter_info_5);
        textView6 = (TextView) findViewById(R.id.tv_bloter_info_6);
        textView7 = (TextView) findViewById(R.id.tv_bloter_info_7);
        textView8 = (TextView) findViewById(R.id.tv_bloter_info_8);
        textView9 = (TextView) findViewById(R.id.tv_bloter_info_9);
        textView10 = (TextView) findViewById(R.id.tv_bloter_info_10);
        textView11 = (TextView) findViewById(R.id.tv_bloter_info_11);
        textView12 = (TextView) findViewById(R.id.tv_bloter_info_12);
        mOrderListView = (ListView) findViewById(R.id.lv_order);

        findViewById(R.id.btn_refund).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                L.d("流水号：" + info.getSerialNum());
                requestBlotterInfo1(info.getOriginalSerialNum());
                findViewById(R.id.ly_blotter_refund).setVisibility(View.GONE);
                findViewById(R.id.btn_refund).setVisibility(View.GONE);
                findViewById(R.id.ly_blotter_blotter).setVisibility(View.VISIBLE);
                findViewById(R.id.ly_good_info).setVisibility(View.VISIBLE);
            }
        });

        if (type == 1) {
            //消息点击
            int intExtra = getIntent().getIntExtra("refund", 0);
            if (intExtra==1){
                mAiJuTitleBarView.getRightTextView().setVisibility(View.GONE);
            }
            requestBlotterInfo1(id);
        } else {
            requestBlotterInfo();
        }
        goodNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (findViewById(R.id.ly_blotter_detail).getVisibility() == View.GONE) {
                    findViewById(R.id.ly_blotter_detail).setVisibility(View.VISIBLE);
                    final ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
                    scrollView.post(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                        }
                    });
                    Drawable drawable = getResources().getDrawable(R.mipmap.icon_blotter_info);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    goodNum.setCompoundDrawables(drawable, null, null, null);
                } else {
                    findViewById(R.id.ly_blotter_detail).setVisibility(View.GONE);
                    Drawable drawable = getResources().getDrawable(R.mipmap.icon_blotter_down);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    goodNum.setCompoundDrawables(drawable, null, null, null);
                }
            }
        });
    }

    private CustomPopWindow customPopWindow;

    /**
     * 退款弹出框
     */
    private void pop(View view) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_more, null);
        //处理popWindow 显示内容
        handleListView(contentView);
        //创建并显示popWindow
        customPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .create()
                .showAsDropDown(view, 100, 0);
    }

    private void handleListView(View contentView) {
        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customPopWindow.dissmiss();
                if (info != null) {
                    Intent intent = new Intent(BlotterInfoActvity.this, RefundActivity.class);
                    intent.putExtra("info", info);
                    startActivity(intent);
                }
            }
        });
    }

    /**
     * 消息点击
     */
    private void requestBlotterInfo1(final String serialNum) {
        mDialogHelper.showLoadingProgressDialog();
        new MessageApi().getBySerialNum(serialNum, mUser.getToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                T.ToastNetError();
                mDialogHelper.dismissProgressDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                mDialogHelper.dismissProgressDialog();
                DataJson dataJson = new DataJson(response);
                if (dataJson.isSuccess()) {
                    info = new Gson().fromJson(dataJson.getData().toString(), new TypeToken<BlotterInfo>() {
                    }.getType());

                    setCenterTitle(info.getReceTypeDesc());
                    price.setText(info.getPrice());
                    textView0.setText(info.getTradeStatus());
                    textView1.setText(info.getCreateDate());
                    textView2.setText(info.getSerialNum());
                    textView3.setText(info.getSellNum());
                    if (info.isPrint()) {
                        textView31.setText("已打印");
                        textView31.setTextColor(Color.parseColor("#6BC7A4"));
                        textView32.setText(info.getPrintSerial());
                        findViewById(R.id.btn_pay_go).setVisibility(View.GONE);
                    } else {
                        findViewById(R.id.btn_pay_go).setVisibility(View.VISIBLE);
                        findViewById(R.id.btn_pay_go).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                PrintManager.getInstance().printReceipt(BlotterInfoActvity.this, serialNum, new PrintManager.PrintCallBack() {
                                    @Override
                                    public void onPrintSuccess() {
                                        if (type == 1) {
                                            requestBlotterInfo1(serialNum);
                                        } else {
                                            requestBlotterInfo();
                                        }
                                    }

                                    @Override
                                    public void onPrintFailure(String msg) {
                                        T.ToastShort(msg);
                                    }
                                });
                            }
                        });
                    }
                    textView4.setText(info.getOperatorName());//收银员
                    textView5.setText(info.getReceTypeDesc());
                    textView6.setText(PriceUtil.formatDouble(info.getSumPrice()));
                    textView7.setText(info.getPrivType());
                    textView8.setText(PriceUtil.formatDouble(info.getPrivPrice()));//优惠金额
                    textView9.setText(PriceUtil.formatDouble(info.getShouldPrice()));
                    textView10.setText(PriceUtil.formatDouble(info.getActualPrice()));
                    textView11.setText(PriceUtil.formatDouble(info.getChangePrice()));
                    // textView12.setText("5%");//费率

                    t1.setContentText(info.getTradeStatus());
                    t2.setContentText(info.getCreateDate());
                    t3.setContentText(info.getSellNum());
                    t4.setContentText(info.getOriginalSerialNum());
                    t5.setContentText(info.getOperatorName());
                    t6.setContentText(info.getReceTypeDesc());
                    t7.setContentText(info.getPrice());
                    t8.setContentText(info.getRemark());


                    goodNum.setText("" + info.getDetails().size());
                    mOrderListView.setAdapter(new MyBaseAdapter(BlotterInfoActvity.this, info.getDetails()));

                    if (!TextUtils.isEmpty(info.getTradeStatus())) {
                        if (info.getTradeStatus().equals("已全额退款")) {
                            imageView.setVisibility(View.GONE);
                        }
                        if (info.getTradeStatus().equals("已部分退款")) {
                            t1.getContentTextView().setTextColor(Color.parseColor("#ff9500"));
                            textView0.setTextColor(Color.parseColor("#ff9500"));
                        }
                    }

                } else {
                    T.ToastShort(dataJson.getMsg());
                }
            }
        });
    }

    /**
     * 流水点击
     */
    private void requestBlotterInfo() {
        mDialogHelper.showLoadingProgressDialog();
        new BlotterApi().blotterGet(id, mUser.getToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                T.ToastNetError();
                mDialogHelper.dismissProgressDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                mDialogHelper.dismissProgressDialog();
                DataJson dataJson = new DataJson(response);
                if (dataJson.isSuccess()) {
                    info = new Gson().fromJson(dataJson.getData().toString(), new TypeToken<BlotterInfo>() {
                    }.getType());
                    price.setText(info.getPrice());
                    textView0.setText(info.getTradeStatus());
                    textView1.setText(info.getCreateDate());
                    textView2.setText(info.getSerialNum());
                    textView3.setText(info.getSellNum());
                    if (info.isPrint()) {
                        textView31.setText("已打印");
                        textView31.setTextColor(Color.parseColor("#6BC7A4"));
                        textView32.setText(info.getPrintSerial());
                        findViewById(R.id.btn_pay_go).setVisibility(View.GONE);
                    } else {
                        findViewById(R.id.btn_pay_go).setVisibility(View.VISIBLE);
                        findViewById(R.id.btn_pay_go).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                PrintManager.getInstance().printReceipt(BlotterInfoActvity.this, info.getSerialNum(), new PrintManager.PrintCallBack() {
                                    @Override
                                    public void onPrintSuccess() {
                                        requestBlotterInfo();
                                    }

                                    @Override
                                    public void onPrintFailure(String msg) {
                                        T.ToastShort(msg);
                                    }
                                });
                            }
                        });
                    }
                    textView4.setText(info.getOperatorName());//收银员
                    textView5.setText(info.getReceTypeDesc());
                    textView6.setText(info.getSumPrice());
                    textView7.setText(info.getPrivType());
                    textView8.setText(info.getPrivPrice());//优惠金额
                    textView9.setText(info.getShouldPrice());
                    textView10.setText(info.getActualPrice());
                    textView11.setText(info.getChangePrice());
                    // textView12.setText("5%");//费率

                    t1.setContentText(info.getTradeStatus());
                    t2.setContentText(info.getCreateDate());
                    t3.setContentText(info.getSerialNum());
                    t4.setContentText(info.getOriginalSerialNum());
                    t5.setContentText(info.getOperatorName());
                    t6.setContentText(info.getReceTypeDesc());
                    t7.setContentText(info.getPrice());
                    t8.setContentText(info.getRemark());

                    if (!TextUtils.isEmpty(info.getTradeStatus())) {
                        if (info.getTradeStatus().equals("已全额退款")) {
                            imageView.setVisibility(View.GONE);
                        }
                        if (info.getTradeStatus().equals("已部分退款")) {
                            t1.getContentTextView().setTextColor(Color.parseColor("#ff9500"));
                            textView0.setTextColor(Color.parseColor("#ff9500"));
                        }
                    }

                    goodNum.setText("" + info.getDetails().size());
                    mOrderListView.setAdapter(new MyBaseAdapter(BlotterInfoActvity.this, info.getDetails()));
                } else {

                }
            }
        });
    }

    private final class MyBaseAdapter extends BaseAdapter {

        private Context context;
        private List<BlotterInfo.Details> clerks;

        public MyBaseAdapter(Context context, List<BlotterInfo.Details> clerks) {
            this.context = context;
            this.clerks = clerks;
        }

        @Override
        public int getCount() {
            return clerks.size();
        }

        @Override
        public Object getItem(int position) {
            return clerks.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View rootView = LayoutInflater.from(context).inflate(R.layout.item_order, parent, false);

            TextView price = (TextView) rootView.findViewById(R.id.tv_order_price);
            TextView num = (TextView) rootView.findViewById(R.id.tv_order_num);
            TextView code = (TextView) rootView.findViewById(R.id.tv_order_code);
            TextView name = (TextView) rootView.findViewById(R.id.tv_order_name);

            BlotterInfo.Details good = clerks.get(position);
            price.setText(good.getPrice());
            num.setText("x" + good.getNum());
            code.setText(good.getCode());
            name.setText(good.getGoodsName());
            return rootView;
        }
    }
}
